package com.ctsi.security.event.organ;

import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.OrganiseIn;
import com.ctsi.security.PermissionRole;
import com.ctsi.security.domain.SRoleUser;
import com.ctsi.security.manager.impl.SecurityImpl;

import java.util.*;


public class OrganEventService {

	private MybatisGenericDao dao = null;
	private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OrganEventService.class);
	private OrganiseIn organiseIn;
	private PermissionRole sroleService;

	// 删除登陆用户
	public void delLoginUserEvent(String userLoginId) {
		// 查询是否有数据
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// loginId=?";
		// Object[] args = { userLoginId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("loginId", userLoginId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			logger.info("权限角色删除登录用户：角色为{}", sroleUser.getRoleId());
			logger.info("权限角色删除登录用户：loginId为{}", sroleUser.getLoginId());
			logger.info("权限角色删除登录用户：loginName为{}", sroleUser.getLoginName());
			// dao.removeObject(com.gentlesoft.security.domain.SRoleUser.class,
			// sroleUser.getRoleUserId());
			dao.remove(sroleUser);
		}
	}

	// 删除用户
	public void delUserEvent(String partyId) {
		// 查询是否有数据
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { partyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", partyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			logger.info("权限角色删除用户：角色为{}", sroleUser.getRoleId());
			logger.info("权限角色删除用户：loginId为{}", sroleUser.getLoginId());
			logger.info("权限角色删除用户：partyId为{}", sroleUser.getPartyId());
			logger.info("权限角色删除用户：loginName为{}", sroleUser.getLoginName());
			// dao.removeObject(com.gentlesoft.security.domain.SRoleUser.class,
			// sroleUser.getRoleUserId());
			dao.remove(sroleUser);
			// 清除缓存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	public int getRef(String roleId, String partyId) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", partyId);
		params.put("roleId", roleId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		if (listSRoleUser == null || listSRoleUser.size() == 0)
			return 0;
		else
			return listSRoleUser.get(0).getRefCount();
	}

	// 删除组织
	public void delOrganEvent(String partyId) {
		// 查询是否有数据
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", partyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			logger.info("权限角色删除组织：角色为{}", sroleUser.getRoleId());
			logger.info("权限角色删除组织：partyId为{}", sroleUser.getPartyId());
			logger.info("权限角色删除组织：partyName为{}", sroleUser.getLoginName());
			// dao.removeObject(com.gentlesoft.security.domain.SRoleUser.class,
			// sroleUser.getRoleUserId());
			dao.remove(sroleUser);
		}
	}

	// 删除用户组
	public void delUserGroupEvent(String partyId, List<Organise> listOrgan, List<Person> listPersons) {
		// 查询是否有数据
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", partyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			// 删除所有子组织
			for (int j = 0; j < listOrgan.size(); j++) {
				Organise organ = listOrgan.get(j);
				this.delAutoParty(sroleUser.getRoleId(), organ.getPartyId(), SRoleUser.typeOrgan);
			}
			// 删除所有登陆用户
			for (int j = 0; j < listPersons.size(); j++) {
				Person person = listPersons.get(j);
				this.delAutoParty(sroleUser.getRoleId(), person.getPartyId(), SRoleUser.typeUser);
			}
			// 删除当前用户组
			logger.info("权限角色删除用户组：partyId为{}", sroleUser.getPartyId());
			logger.info("权限角色删除用户组：partyName为{}", sroleUser.getLoginName());
			dao.remove(sroleUser);
		}

	}

	// 自动删除用户、组织和用户组
	public void delAutoParty(String roleId, String partyId, String type) {
		String typeName = "用户";
		if (type.equals(SRoleUser.typeOrgan)) {
			typeName = "组织";
		} else if (type.equals(SRoleUser.typeUserGroup)) {
			typeName = "用户组";
		}
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// roleId=? and partyId=? ";
		// Object[] args = { roleId, partyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("roleId", roleId);
		params.put("partyId", partyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			int refCount = sroleUser.getRefCount();
			if (refCount > 1) {
				// 更新
				logger.info("权限角色更新{}的角色ID为{}", typeName, sroleUser.getRoleId());
				logger.info("权限角色更新{}的partyID为{}", typeName, sroleUser.getPartyId());
				sroleUser.setRefCount(sroleUser.getRefCount() - 1);
				// dao.updateObject(sroleUser);
				dao.update(sroleUser);
			} else {
				// 删除
				logger.info("权限角色删除{}的角色ID为{}", typeName, sroleUser.getRoleId());
				logger.info("权限角色删除{}的partyID为{}", typeName, sroleUser.getPartyId());
				// dao.removeObject(
				// com.gentlesoft.security.domain.SRoleUser.class,
				// sroleUser.getRoleUserId());
				dao.remove(sroleUser);
				// 清除缓存
				SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
			}
		}
	}

	// 登陆用户自动加入
	public void addAutoLoginUser(String roleId, String partyId, String loginId, String loginName) {
		String typeName = "登陆用户";
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// loginId=? and roleId=?";
		// Object[] args = { loginId, roleId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("loginId", loginId);
		params.put("roleId", roleId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		if (listSRoleUser.size() > 0) {
			for (int i = 0; i < listSRoleUser.size(); i++) {
				SRoleUser sroleUser = listSRoleUser.get(i);
				// 更新
				logger.info("权限角色更新{}的角色ID为{}", typeName, sroleUser.getRoleId());
				logger.info("权限角色更新{}的partyID为{}", typeName, sroleUser.getPartyId());
				logger.info("权限角色更新{}的loginName为{}", typeName, sroleUser.getLoginName());
				sroleUser.setRefCount(sroleUser.getRefCount() + 1);
				// dao.updateObject(sroleUser);
				dao.update(sroleUser);
			}
		} else {
			logger.info("权限角色新增{}的角色ID为{}", typeName, roleId);
			logger.info("权限角色新增{}的LoginName为{}", typeName, loginName);
			SRoleUser sroleUser = new SRoleUser();
			sroleUser.setRoleId(roleId);
			sroleService.setJoinWay(SRoleUser.joinWayAuto,sroleUser);
			sroleUser.setLoginId(loginId);
			sroleUser.setLoginName(loginName);
			sroleUser.setPartyId(partyId);
			sroleUser.setRefCount(1);
			sroleUser.setType(SRoleUser.typeUser);
			// dao.saveObject(sroleUser);
			sroleUser.setRoleUserId(UUID.randomUUID().toString());
			dao.insert(sroleUser);
			// 清除緩存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	// 组织自动加入
	public void addAutoOrgan(String roleId, String partyId, String partyName) {
		String typeName = "组织";
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=? and roleId=?";
		// Object[] args = { partyId, roleId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(2);
		params.put("partyId", partyId);
		params.put("roleId", roleId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		if (listSRoleUser.size() > 0) {
			for (int i = 0; i < listSRoleUser.size(); i++) {
				SRoleUser sroleUser = listSRoleUser.get(i);
				// 更新
				logger.info("权限角色更新{}的角色ID为{}", typeName, sroleUser.getRoleId());
				logger.info("权限角色更新{}的partyID为{}", typeName, sroleUser.getPartyId());
				sroleUser.setRefCount(sroleUser.getRefCount() + 1);
				// dao.updateObject(sroleUser);
				dao.update(sroleUser);
			}
		} else {
			// 新增
			logger.info("权限角色新增{}的角色ID为{}", typeName, roleId);
			logger.info("权限角色新增{}的partyId为{}", typeName, partyId);
			SRoleUser sroleUser = new SRoleUser();
			sroleUser.setRoleId(roleId);
			sroleService.setJoinWay(SRoleUser.joinWayAuto,sroleUser);
			sroleUser.setPartyId(partyId);
			sroleUser.setRefCount(1);
			sroleUser.setType(SRoleUser.typeOrgan);
			sroleUser.setLoginName(partyName);
			sroleUser.setRoleUserId(UUID.randomUUID().toString());
			dao.insert(sroleUser);
			// dao.saveObject(sroleUser);

		}
	}

	// 人员离开用户组
	public void userLeaveUserGroupEvent(String userGroupPartyId, String userPartyId) {
		// 根据userGroupPartyId查询角色用户表中是否有该用户组
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { userGroupPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", userGroupPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			this.delAutoParty(sroleUser.getRoleId(), userPartyId, SRoleUser.typeUser);
			// 清除缓存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	// 人员加入用户组
	public void userJoinUserGroupEvent(String userGroupPartyId, String userPartyId, List<String> listLoginId, List<String> listLoginName) {
		// 根据userGroupPartyId查询角色用户表中是否有该用户组
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", userGroupPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int j = 0; j < listLoginId.size(); j++) {
				String loginId = listLoginId.get(j);
				String loginName = listLoginName.get(j);
				this.addAutoLoginUser(sroleUser.getRoleId(), userPartyId, loginId, loginName);
			}
			// 清除缓存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	// 人员离开组织
	public void userLeaveOrganEvent(String organPartyId, String userPartyId) {
		// 根据organPartyId查询角色用户表中是否有该用户组
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { organPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", organPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int n = 0; n < sroleUser.getRefCount(); n++) {
				this.delAutoParty(sroleUser.getRoleId(), userPartyId, SRoleUser.typeUser);
			}
			// 清除缓存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	// 人员加入组织
	public void userJoinOrganEvent(String organPartyId, String userPartyId, List<String> listLoginId, List<String> listLoginName) {
		// 根据organPartyId查询角色用户表中是否有该用户组
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { organPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", organPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int n = 0; n < sroleUser.getRefCount(); n++) {
				for (int j = 0; j < listLoginId.size(); j++) {
					String loginId = listLoginId.get(j);
					String loginName = listLoginName.get(j);
					this.addAutoLoginUser(sroleUser.getRoleId(), userPartyId, loginId, loginName);
				}
			}
			// 清除缓存
			SecurityImpl.removeCacheUserRoles(sroleUser.getLoginId());
		}
	}

	// 组织加入用户组
	public void organJoinUserGroupEvent(String userGroupPartyId, String organPartyId, String organPartyName) {
		this.organJoinOrganOrUserGroup(userGroupPartyId, organPartyId, organPartyName, SRoleUser.typeUserGroup, new ArrayList<Organise>(), new ArrayList<UserLogin>());
	}

	// 组织离开用户组
	public void organLeaveUserGroupEvent(String userGroupPartyId, String organPartyId) {
		// 根据userGroupPartyId查询角色用户表中是否有该用户组
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { userGroupPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", userGroupPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		// 得到当前组织的所有子组织及子孙人员
		List<SRoleUser> organSons = organiseIn.getOrganOrUserGroupToOrgan(organPartyId, SRoleUser.typeOrgan);
		List<SRoleUser> userSons = organiseIn.getOrganOrUserGroupToLoginUser(organPartyId, SRoleUser.typeOrgan);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int n = 0; n < sroleUser.getRefCount(); n++) {
				// 删除当前组织
				this.delAutoParty(sroleUser.getRoleId(), organPartyId, SRoleUser.typeOrgan);
				// 删除当前子孙组织
				for (SRoleUser item : organSons) {
					this.delAutoParty(sroleUser.getRoleId(), item.getPartyId(), SRoleUser.typeOrgan);
				}
				// 删除当前子孙登录用户
				for (SRoleUser item : userSons) {
					this.delAutoParty(sroleUser.getRoleId(), item.getPartyId(), SRoleUser.typeUser);
				}
			}
		}
	}

	public void organLeaveOrganEventWithRefresh(String parentPartyId, String sonPartyId, List<Organise> listOrgan, List<Person> listPerson) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", parentPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		Set<String> ids = new HashSet<String>();
		for (SRoleUser sRoleUser : listSRoleUser) {
			ids.add(sRoleUser.getRoleId());
		}

		for (String id : ids) {
			sroleService.refresh(id);
		}
	}

	// 组织离开组织
	@Deprecated
	public void organLeaveOrganEvent(String parentPartyId, String sonPartyId, List<Organise> listOrgan, List<Person> listPerson) {
		// 根据parentPartyId查询角色用户表中是否有该组织
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { parentPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", parentPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int n = 0; n < sroleUser.getRefCount(); n++) {
				// 删除当前组织
				this.delAutoParty(sroleUser.getRoleId(), sroleUser.getPartyId(), SRoleUser.typeOrgan);
				// 删除子组织
				for (int j = 0; j < listOrgan.size(); j++) {
					Organise localOrgan = listOrgan.get(j);
					this.delAutoParty(sroleUser.getRoleId(), localOrgan.getPartyId(), SRoleUser.typeOrgan);
				}
				// 删除用户
				for (int j = 0; j < listPerson.size(); j++) {
					Person localPerson = listPerson.get(j);
					this.delAutoParty(sroleUser.getRoleId(), localPerson.getPartyId(), SRoleUser.typeUser);
				}
			}
		}
	}

	// 组织加入组织
	public void organJoinOrganEvent(String parentOrganPartyId, String organPartyId, String organPartyName, List<Organise> listOrgan, List<UserLogin> listUserLogin) {
		this.organJoinOrganOrUserGroup(parentOrganPartyId, organPartyId, organPartyName, SRoleUser.typeOrgan, listOrgan, listUserLogin);
	}

	// 组织加入组织或用户组
	public void organJoinOrganOrUserGroup(String parentOrganOrUserGroupPartyId, String organPartyId, String organPartyName, String type, List<Organise> listOrgan, List<UserLogin> listUserLogin) {
		// 根据userGroupPartyId查询角色用户表中是否有该用户组
		// String hsql = "from com.gentlesoft.security.domain.SRoleUser where
		// partyId=?";
		// Object[] args = { parentOrganOrUserGroupPartyId };
		// List<SRoleUser> listSRoleUser = dao.findAll(hsql, args);
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("partyId", parentOrganOrUserGroupPartyId);
		List<SRoleUser> listSRoleUser = dao.find(SRoleUser.class, params);
		for (int i = 0; i < listSRoleUser.size(); i++) {
			SRoleUser sroleUser = listSRoleUser.get(i);
			for (int n = 0; n < sroleUser.getRefCount(); n++) {
				this.addAutoOrgan(sroleUser.getRoleId(), organPartyId, organPartyName);
				// 组织加入组织时加入子组织和人员
				for (int j = 0; j < listOrgan.size(); j++) {
					Organise localOrgan = listOrgan.get(j);
					this.addAutoOrgan(sroleUser.getRoleId(), localOrgan.getPartyId(), localOrgan.getPartyName());
				}
				for (int j = 0; j < listUserLogin.size(); j++) {
					UserLogin userLogin = listUserLogin.get(j);
					Person person = OrganiseFactoryBean.getInstance().getPersonServiceProxy().findPersonById(userLogin.getPartyId());
					this.addAutoLoginUser(sroleUser.getRoleId(), userLogin.getPartyId(), userLogin.getId(), person.getFullName());
				}
			}
		}
	}

	public MybatisGenericDao getDao() {
		return dao;
	}

	public void setDao(MybatisGenericDao dao) {
		this.dao = dao;
	}

	public OrganiseIn getOrganiseIn() {
		return organiseIn;
	}

	public void setOrganiseIn(OrganiseIn organiseIn) {
		this.organiseIn = organiseIn;
	}

	public void setSroleService(PermissionRole sroleService) {
		this.sroleService = sroleService;
	}


}
